import 'package:aichat_flutter_wallet/module/module_browser/viewmodel/before_browser.dart';
import 'package:aichat_flutter_wallet/module/module_browser/viewmodel/we3_method.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/provider/dapp_cache_provider.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/utils/dapp_favorite_util.dart';
import 'package:aichat_flutter_wallet/module_common/bridge/native_channel_bridge.dart';
import 'package:aichat_flutter_wallet/module_common/provider/nav_key.dart';
import 'package:aichat_flutter_wallet/module_common/provider/wallet_info_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';

import '../../../kai_print.dart';
import '../../module_dapp/utils/dapp_cache_util.dart';

class BrowserProvider extends ChangeNotifier {
  InAppWebViewController? webViewController;
  BuildContext? pageContext;
  bool isLoadSuccess = true;
  bool isLoadStop = false;
  double progress = 0;
  bool isLove = false;
  bool isConnectWallet = false;
  Chain? selectChain;
  NodeInfo? nodeInfoData;
  Map<String, dynamic> blockMap = {};
  WebSiteInfoItem? webSiteInfoItem;

  void setProgress(double num) {
    progress = num;
    notifyListeners();
  }

  // 设置当前的网站信息
  void setCurWebsiteInfo({WebSiteInfoItem? website}) {
    webSiteInfoItem = website;
  }

  void setIsLoadStop(bool isLoadStop) {
    isLoadStop = isLoadStop;
    notifyListeners();
  }

  void back(Function? onClose) async {
    bool canBack = await webViewController!.canGoBack();
    if (canBack) {
      clearConnect();
      webViewController?.goBack();
    } else {
      if(onClose!=null){
         onClose();
         return;
      }
      close();
    }
  }

  setController(InAppWebViewController controller) {
    webViewController = controller;
  }

  void initController(controller, context) {
    webViewController = controller;
    pageContext = context;
    // webViewController!.addJavaScriptHandler(
    //     handlerName: 'postMessage',
    //     callback: (args) {
    //       // kaiPrint(args[0]);
    //       // Config.logger.d(args[0]);
    //       // Map<String, dynamic> data = json.decode(args[0]);
    //       // _handleMessage(data);
    //       // _handleOneMoreMessage(data);
    //     });
  }

  void reload() {
    if (!isLoadSuccess) {
      isLoadSuccess = true;
    }
    if (webViewController == null) {
      return;
    }
    clearConnect();
    webViewController!.reload();
  }

  void close() {
    pageContext = NavKey.navKey.currentContext;
    clearConnect();
    Navigator.of(pageContext!).pop();
  }

  setIsLoadingEmpty(bool value) {
    isLoadSuccess = value;
  }

  // 获取网站标题
  Future<String?> getWebsiteTitle() async {
    var title = await webViewController!.getTitle();
    return title;
  }

  // 获取网站logo
  Future<String> getWebsiteLogo() async {
    try {
      var logoList = await webViewController!.getFavicons();
      var logoUri = logoList[0].url;
      kaiPrint('logoUri.origin => ${logoUri.origin}');
      var logo = logoUri.origin + logoUri.path;
      return logo;
    } catch (e) {
      return Future.value('');
    }
  }

  Future<String> getWebsiteUrl() async {
    var logoList = await webViewController!.getFavicons();
    var logoUri = logoList[0].url;
    var url = logoUri.origin;
    return url;
  }

  // 设置连接状态
  void setWalletConnect(bool isConnet) {
    isConnectWallet = isConnet;
  }

  // 清除连接状态
  void clearConnect() {
    isConnectWallet = false;
    selectChain = null;
    nodeInfoData = null;
    blockMap = {};
  }

  // 获取初始化的网络和节点
  Map<String, dynamic> getNetworkAndNode() {
    List<Chain> netWorkList = Web3MethodCall.getNetworkList();
    String walletShortName =
        NavKey.getContext().read<WalletInfoNotifier>().walletChainShortName;
    Chain selectNetwork = netWorkList.firstWhere((element) {
      return element.shortName == walletShortName;
    });
    NodeInfo nodeInfoData1 =
        ObjectBox().nodeInfoModel.getSelectedNodeInfo(walletShortName);
    Map<String, dynamic> map = {};
    map['chain'] = selectNetwork;
    map['node'] = nodeInfoData1;
    return map;
  }

  setNetworkAndNode() {
    Wallet? wallet = NavKey.getContext().read<WalletInfoNotifier>().wallet;
    if (wallet == null) return;
    Map<String, dynamic> map = getNetworkAndNode();
    selectChain = map['chain'];
    nodeInfoData = map['node'];
    notifyListeners();
  }

  // 选中的网络
  void switchChainNet({required String chainIdOx, bool needChangeOx = true}) {
    int num = 0;
    if (needChangeOx) {
      num = hexToDecimal(chainIdOx);
    } else {
      num = int.parse(chainIdOx);
    }
    List<Chain> chainlist = Web3MethodCall.getNetworkList();
    Chain chain = chainlist.firstWhere((element) {
      return element.evmInfo!.chainId == num;
    });

    NodeInfo nodeInfoData1 =
        ObjectBox().nodeInfoModel.getSelectedNodeInfo(chain.shortName);
    selectChain = chain;
    nodeInfoData = nodeInfoData1;
    // 重置 walletInfo 信息
    int walletId = NavKey.getContext().read<WalletInfoNotifier>().walletId;
    WalletInfo? info = ObjectBox().walletInfoModel.getWalletInfoByWalletIdAndChain(walletId, chain.shortName);
    if (null != info) {
      NavKey.getContext().read<WalletInfoNotifier>().updateCurrentWallet(info);
    }
    notifyListeners();
  }

// 设置选择的网络
  void setSelectChain(Map<String, dynamic> map) {
    selectChain = map['chain'];
    nodeInfoData = map['node'];
    blockMap = map['block'];
    notifyListeners();
  }

// 16进制转为10进制
  int hexToDecimal(String hex) {
    int decimal = int.parse(hex);
    return decimal;
  }

  void setLove(bool value) {
    isLove = value;
  }

  void doUpdate() {
    notifyListeners();
  }

  void love(String url, {Function? callback}) async {
    DAppBean dappBean = await getDappBean(url);
    pageContext = NavKey.getContext();
    DAppFavoriteUtil.showSetFavorite(pageContext!, onConfirm: (value) {
      setLove(value);
      if (callback != null) {
        callback(value);
      }
    },
        onClose: () {},
        DApp: dappBean,
        needToast: true,
        title: 'Favorites Dapp');
  }

  Future<DAppBean> getDappBean(String url) async {
    String? name = '';
    String logo = '';
    String tag = '';
    String userId = '';
    try {
      userId = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
      BeforeBrowserController controller = BeforeBrowserController();
      if (controller.websiteUrl == url && !controller.isSearchIn) {
        name = controller.websiteName;
        logo = controller.websiteImg;
        tag = controller.websiteTag;
      } else {
        name = await getWebsiteTitle() ?? '';
        logo = await getWebsiteLogo();
      }
    } catch (e) {
      kaiPrint(e);
    }

    DAppBean dappBean = DAppBean.optional(
        name: name,
        url: url,
        logo: logo,
        uid: userId,
        statement: tag,
        chains: [1]);
    return Future.value(dappBean);
  }

  void addCacheInfo(String url) async {
    // String extractedUrl = Uri.parse(url).origin;
    //因为https://face.xjlqingjie.com/stk-face这里这个链接，origin没办法访问，所以放开了这里，直接存整个url，之后要怎么处理再改 --2024.2.7
    String extractedUrl = url;
    DAppBean dappBean = await getDappBean(extractedUrl);
    // 前置当前的网站信息
    WebSiteInfoItem webSiteInfoItem = WebSiteInfoItem(
        websiteImg: dappBean.logo ?? '',
        websiteName: dappBean.name ?? "",
        websiteUrl: dappBean.url ?? "");
    setCurWebsiteInfo(website: webSiteInfoItem);
    pageContext = NavKey.getContext();
    final isExisted =
        await Provider.of<DAppCacheProvider>(pageContext!, listen: false)
            .isCacheDAppExisted(dappBean);
    if (!isExisted) {
      // Log.logger.e('添加历史缓存:' + dappBean.toString());
      await Provider.of<DAppCacheProvider>(pageContext!, listen: false)
          .addCache(dappBean);
      return;
    }
    List<DAppBean> totalList =
        await Provider.of<DAppCacheProvider>(pageContext!, listen: false)
            .cacheDAppList
            .toList(growable: false);
    if (totalList.length >= 6) {
      var delIndex = 0;
      for (int i = totalList.length - 1; i >= 0; i--) {
        var dApp = totalList[i];
        if (dApp.url == url) delIndex = i;
      }
      // 删除 第 0 条 以及 第6条
      final List<DAppBean> delItems = [];
      delItems.add(totalList[delIndex]);
      if (totalList.sublist(6).length > 0)
        delItems.addAll(totalList.sublist(6));
      // 先删除 后添加
      await DAppCacheUtil.deleteAllHistory(pageContext!, dApps: delItems);
    } else {
      await DAppCacheUtil.deleteHistoryOne(pageContext!, dApp: dappBean);
    }
    // Log.logger.e('添加历史缓存:' + dappBean.toString());
    await Provider.of<DAppCacheProvider>(pageContext!, listen: false)
        .addCache(dappBean);
  }
}
